package com.gaga.common.utils.audio;

import cn.hutool.core.thread.ThreadUtil;

import javax.sound.sampled.FloatControl;
import javax.sound.sampled.SourceDataLine;

public class AudioVolumeController {
    private FloatControl gainControl;

    /**
     * 初始化音量控制器
     *
     * @param line 音频输出线路
     */

    public void initVolumeControl(SourceDataLine line) {
        if (line.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
            gainControl = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
        } else {
            System.err.println("当前设备不支持主音量控制");
        }
    }

    /**
     * 设置音量等级
     *
     * @param volume 音量值（范围0.0-1.0）
     */
    public void setVolume(float volume) {
        if (gainControl != null) {
            // 转换线性音量到分贝范围（-80dB到+6dB）
            float dB = (float) (Math.log10(volume == 0 ? 0.000 : volume) * 20);
            dB = Math.max(gainControl.getMinimum(), Math.min(dB, gainControl.getMaximum()));
            gainControl.setValue(dB);
        }
    }

    public void setFadeVolume(float targetVolume, int durationMs) {
        final float startDb = gainControl.getValue();
        final float targetDb = (float) (Math.log10(targetVolume) * 20);

        ThreadUtil.execute(() -> {
            int steps = durationMs / 50;
            for (int i = 0; i <= steps; i++) {
                float progress = (float) i / steps;
                float currentDb = startDb + (targetDb - startDb) * progress;
                gainControl.setValue(currentDb);
                ThreadUtil.sleep(50);
            }
        });
    }
}